import { db } from './connect'
import { Random } from 'mockjs'
import { findOne } from './query'

export function initTable() {
  // 创建categories表
  db().exec(`
    CREATE TABLE IF NOT EXISTS categories (
      id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      name TEXT NOT NULL,
      created_at TEXT NOT NULL
    );
  `)

  // 创建contents表
  db().exec(`
    CREATE TABLE IF NOT EXISTS contents (
      id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      title TEXT NOT NULL,
      content TEXT NOT NULL,
      category_id INTEGER,
      created_at TEXT NOT NULL
    );
  `)

  // 创建config表，存储全局配置信息

  db().exec(`
    CREATE TABLE IF NOT EXISTS config (
      id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      content TEXT NOT NULL
    );
  `)

  initData()
}

function initData() {
  const isInit = findOne('select * from contents')
  console.log(isInit)
  if (isInit) return
  db().exec(`
    INSERT INTO config (content) VALUES ('{"shortcut":"Control+Shift+L","databaseDirectory":"abc"}');
`)
  // 1-10个分类，每个分类下有1-20篇文章
  for (let i = 1; i < 11; i++) {
    const name = Random.title(5, 10)
    // 向category表插入数据
    db().exec(`
      INSERT INTO categories (name, created_at) VALUES ('${name}', datetime('now', '+8 hours'));
    `)

    for (let j = 1; j < 20; j++) {
      const title = Random.title(5, 10)
      const content = Random.paragraph(5, 10)
      // 向category表插入数据
      db().exec(`
        INSERT INTO contents (title, content, category_id, created_at) VALUES ('${title}', '${content}', ${i}, datetime('now', '+8 hours'));
      `)
    }
  }
}
